﻿using System;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace SharePoint.Contrib.Extensions
{
    /// <summary>
    /// Extensions for the XElement class
    /// </summary>
    public static class XElementExtensions
    {
        /// <summary>
        /// Converts the value of the XElement to &lt;T&gt;
        /// </summary>
        /// <typeparam name="T">type to convert to</typeparam>
        public static T OfType<T>(this XElement instance)
        {
            if (instance == null)
            {
                return default(T);
            }


            if (string.IsNullOrEmpty(instance.Value) == false)
            {
                T obj = default(T);

                obj = GenericDataConverter<T>.Convert(instance.Value);
                return obj;
            }

            return default(T);

        }

        /// <summary>
        /// Converts the <see cref="T:System.Xml.Linq.XElement"/> to an instance of <see cref="T:System.Xml.XmlNode"/>.
        /// </summary>
        public static XmlNode ToXmlNode(this XElement instance)
        {
            return instance.ToXmlDocument() as XmlNode;

        }

        /// <summary>
        /// Converts the <see cref="T:System.Xml.Linq.XElement"/> to an instance of <see cref="T:System.Xml.XmlDocument"/>.
        /// </summary>
        public static XmlDocument ToXmlDocument(this XElement instance)
        {
            using (XmlReader xmlReader = instance.CreateReader())
            {
                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(xmlReader);

                return xmlDoc;

            }

        }

        /// <summary>
        /// Removes the namespace attribute/s in the xml
        /// </summary>
        /// <param name="namespaceAttributeName">the name of the namespace attribute (f.e. xmlns)</param>
        public static XElement RemoveNamespace(this XElement instance, string namespaceAttributeName)
        {
            return XElement.Parse(Regex.Replace(instance.ToString(), String.Format(@"({0}:?[^=]*=[""][^""]*[""])", namespaceAttributeName), string.Empty,
                                                RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline));
        }
    }

}
